package com.lanxiao.cloud.common.fill;

import cn.hutool.core.collection.CollUtil;
import java.util.Collection;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author ：qiaoliang
 * @date ：2021-04-02
 */
@Component
public class FillHandleFactory implements IFillHandleFactory, ApplicationContextAware {

  private final Map<FillType, IFillHandleService> fillTypeFillHandleServiceMap;

  public FillHandleFactory() {
    this.fillTypeFillHandleServiceMap = new EnumMap<>(FillType.class);;
  }

  @Override
  public <T extends V,V> void fill(List<T> list, List<FillHandle<V,?,?>> fillHandles) {
    if(CollUtil.isEmpty(list) || CollUtil.isEmpty(fillHandles)){
      return;
    }
    fillHandles.parallelStream().filter(Objects::nonNull).forEach(fillHandle -> this.fill(list, fillHandle));
  }

  @Override
  public <T extends V,V> void fill(List<T> list, FillHandle<V, ?, ?> fillHandle) {
    if(CollUtil.isEmpty(list) || Objects.isNull(fillHandle)){
      return;
    }

    IFillHandleService fillHandleService = fillTypeFillHandleServiceMap.get(fillHandle.type());
    if(Objects.nonNull(fillHandleService)){
      fillHandleService.handle(list, fillHandle);
    }
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    Collection<IFillHandleService> values = applicationContext.getBeansOfType(
        IFillHandleService.class).values();
    values.forEach(v-> fillTypeFillHandleServiceMap.put(v.type(),v));
  }

}
